package com.github.wxiaoqi.security.auth.controller;

import com.github.wxiaoqi.security.auth.feign.IUserinfoService;
import com.github.wxiaoqi.security.auth.service.AuthService;
import com.github.wxiaoqi.security.auth.util.user.JwtAuthenticationRequest;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.msg.ResponseCode;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("jwt")
@Slf4j
public class AuthController {
    @Value("${jwt.token-header}")
    private String tokenHeader;

    @Autowired
    private AuthService authService;
    @Autowired
    private IUserinfoService userinfoService;
    @Autowired
    private RedisTemplate redisTemplate;
    
    @RequestMapping(value = "token", method = RequestMethod.POST)
    public ObjectRestResponse<String> createAuthenticationToken(
            @RequestBody JwtAuthenticationRequest authenticationRequest) throws Exception {
        log.info(authenticationRequest.getUsername()+" require logging...");
        final String token = authService.login(authenticationRequest);
        return new ObjectRestResponse<>().data(token);
    }

    @RequestMapping(value = "refresh", method = RequestMethod.GET)
    public ObjectRestResponse<String> refreshAndGetAuthenticationToken(
            HttpServletRequest request) throws Exception {
        String token = request.getHeader(tokenHeader);
        String refreshedToken = authService.refresh(token);
        return new ObjectRestResponse<>().data(refreshedToken);
    }

    @RequestMapping(value = "verify", method = RequestMethod.GET)
    public ObjectRestResponse<?> verify(String token) throws Exception {
        authService.validate(token);
        return new ObjectRestResponse<>();
    }
    
    /**
     * 获取用户登录授权token
     * 
     * */
    @RequestMapping(value = "apiToken", method = RequestMethod.POST)
    public Map<String,Object> verify(@RequestBody JwtAuthenticationRequest authenticationRequest) throws Exception {
    	Map<String,Object> respMap=new HashMap<String,Object>();
    	String token="";
    	//校验参数
    	if(StringUtils.isEmpty(authenticationRequest.getUsername())){//登录用户名不能为空
    		respMap.put("sucess", false);
    		respMap.put("code", ResponseCode.USERNAME_NOTNULL.getCode());//
			respMap.put("msg", ResponseCode.USERNAME_NOTNULL.getMessage());
			return respMap;
    	}
		if(StringUtils.isEmpty(authenticationRequest.getPassword())){//登录密码不能为空
			respMap.put("sucess", false);
    		respMap.put("code", ResponseCode.PASSWORD_NOTNULL.getCode());//
			respMap.put("msg", ResponseCode.PASSWORD_NOTNULL.getMessage());
			return respMap;
		}
		Map<String,Object>responsedata=userinfoService.validate(authenticationRequest);
		if(ResponseCode.OK.getCode().equals(responsedata.get("code"))){//登录成功，获取token
			try {
				token = authService.createCrmapiToken(authenticationRequest.getUsername(),authenticationRequest.getPassword());
				if(StringUtils.isEmpty(token)){
					log.info("授权获取TOKEN为空 :"+token);
					respMap.put("sucess", false);
		    		respMap.put("code", ResponseCode.LOGIN_ERROR.getCode());//
					respMap.put("msg", ResponseCode.LOGIN_ERROR.getMessage());
					return respMap;
				}
				redisTemplate.opsForValue().set("login:token_"+authenticationRequest.getUsername(),token,7200,TimeUnit.SECONDS);
				responsedata.put("token", token);
			} catch (Exception e) {
				log.info("授权获取TOKEN数据报错:"+e.getMessage());
				e.printStackTrace();
				respMap.put("sucess", false);
	    		respMap.put("code", ResponseCode.LOGIN_ERROR.getCode());//
				respMap.put("msg", ResponseCode.LOGIN_ERROR.getMessage());
				return respMap;
			}
		}
		return responsedata;
	}
}